<?php
	date_default_timezone_set('America/New_York');
	require("../header.php");
	require("../quizFunctions.php");
	$username = $_SESSION['username'];
	
	checkIfUserTookQuiz();
		
	if($_SERVER['REQUEST_METHOD'] == 'POST'):
		if(isset($_POST['userWantsToTakeQuiz'])):			
			startQuiz();
		elseif(isset($_POST['submitAnswer'])):
			processUsersAnswer();
		endif;
	elseif($_SERVER['REQUEST_METHOD'] == 'GET'):
		header("Location: /proj1/index.php");
	endif;
	
	function checkIfUserTookQuiz()
	{
		$username = $_SESSION['username'];
		if(userHasTakenTodaysQuiz($username)):
			header("Location: /proj1/index.php");
		else:
			return;
		endif;
	}
	
	function startQuiz()
	{
		// TODO: make sure to uncomment this. We want the cookie after testing.
		rememberInCookieUserStartedTodaysQuiz();
		$todaysQuizNum = getTodaysRandomQuizNumber();
		$_SESSION['currentQuizNumber'] = $todaysQuizNum;
		$_SESSION['ongoingQuiz'] = true;
		// $_SESSION['lastQuizStartDate'] = new DateTime();
		$quizInfo = getQuizInfo($todaysQuizNum);

		setSessionWithQuizInfo($quizInfo);
		setSessionWithUserInfo();
		
		displayQuestion(1); /* display first question */
		/* echo var_dump($_SESSION) . "<br/>";
		echo "Today's quiz number: $todaysQuizNum <br/>";
		echo "starting the quiz!<br/>"; */
	}
	
	function processUsersAnswer()
	{
		//echo var_dump($_POST['answer']) . "<br />";
		//echo $_POST['answer'] . " was chosen. <br />";
		$indexOfAnswer = $_POST['answer'];
		$actualIndexOfAnswer = $_SESSION['currentCorrectAnswerIndex'];
		$correctAnswer = $_SESSION['currentCorrectAnswer'];
		if($indexOfAnswer == $actualIndexOfAnswer):
			echo "Your answer of '{$correctAnswer}' is correct.  </br></br><hr>";
			$_SESSION['userCorrect']++;			
		else:
			$incorrectAnswer = $_SESSION['currentPossibleAnswers'][$indexOfAnswer];
			echo "Your answer of '{$incorrectAnswer}' is incorrect.  The correct
					answer is '{$correctAnswer}'.</br></br><hr>";
			$_SESSION['userIncorrect']++;
		endif;
		$_SESSION['usersCurrentQuestion']++;
		$nextQuestionToDisplay = $_SESSION['usersCurrentQuestion'];
		$numberOfQuizQuestions = $_SESSION['quizNumOfQuestions'];
		if($nextQuestionToDisplay > $numberOfQuizQuestions):
			displayUserStatsForCurrentQuiz();
			updateQuizzesFileWithUserStats($_SESSION['currentQuizNumber'], $_SESSION['userCorrect'], $_SESSION['userIncorrect'] );
			displayStatsForQuiz($_SESSION['currentQuizNumber']);
			lockoutUserFromQuiz();
		else:
			displayQuestion($nextQuestionToDisplay);
		endif;
		
	}
	
	function lockoutUserFromQuiz()
	{
		$_SESSION['ongoingQuiz'] = false;
	}
	
	function displayStatsForQuiz($quizNumber)
	{
		/* <QuizFileName>#<NumOfQuests>#<NumOfTakers>#<TotCorr>#<TotIncorr> */
		$quizInfo = getQuizInfo($quizNumber);
		$numOfTakers = $quizInfo[2];
		$totalCorrect = $quizInfo[3];
		$totalIncorrect = $quizInfo[4];
		
		echo "<br /> Here are the cumulative stats for Quiz $quizNumber: <br /> <br />";
		$totalQuestions = $totalCorrect + $totalIncorrect;
		$percentRight = ((int)($totalCorrect / $totalQuestions * 10000)) / 100;
		echo "$totalCorrect out of $totalQuestions ($percentRight percent)<br /> ";
		echo "<br /> Log out or return to the quiz home page. Don't forget you can take a quiz each day.<br />";
		
	}
	
	function updateQuizzesFileWithUserStats($quizNumber, $userCorrect, $userIncorrect)
	{
		/* <QuizFileName>#<NumOfQuests>#<NumOfTakers>#<TotCorr>#<TotIncorr> */
		$quizInfo = getQuizInfo($quizNumber);
		$quizInfo[3] += $userCorrect;
		$quizInfo[4] += $userIncorrect;
		$quizInfo = implode("#", $quizInfo) . "\n";
		// echo "updateQuizzesFileWithUserStats(): quiz #: $quizNumber  usercorrect: $userCorrect  
				// userIncorrect $userIncorrect <br/ >";
		// echo "dumping quizInfo (that line from quizzes.txt): " . var_dump($quizInfo) . "<br />";
		$quizIndex = $quizNumber - 1;
		$linesFromQuizzesFile = getAllLinesFromFile("quizzes.txt");
		// echo "dumping all lines from quizzes.txt : " . var_dump($linesFromQuizzesFile) . "<br />";
		$linesFromQuizzesFile[$quizIndex] = $quizInfo;
		// echo "dumping all lines from quizzes.txt (time to write): " . var_dump($linesFromQuizzesFile) . "<br />";
		writeToFileFromArray("quizzes.txt", $linesFromQuizzesFile);
	}
	
	function writeToFileFromArray($filename, $array)
	{
		$fp = fopen($filename, "w");
		if(flock($fp, LOCK_EX)):
			foreach($array as $line):
				fwrite($fp, $line);
				//echo "wrting $line to file";
			endforeach;
			flock($fp, LOCK_UN);
			fclose($fp);		
			return null;
		else: 
			echo "Trouble getting lock. Recursively calling writeToFileFromArray() again.";
			sleep(1);
			writeToFileFromArray();
		endif;
	}
	
	function displayUserStatsForCurrentQuiz()
	{
		$userCorrect = $_SESSION['userCorrect'];
		$userIncorrect = $_SESSION['userIncorrect'];
		$totalQuestions = $userCorrect + $userIncorrect;
		$percentRight = ((int)($userCorrect / $totalQuestions * 10000)) / 100;
		echo "You got $userCorrect questions right out of $totalQuestions ($percentRight percent).<br />";
	}
	
	function displayQuestion($questionNum)
	{
		/* Example question in quiz1.txt
		What is 2*2?#2:4:6:8#1 
		*/
		echo "Question #$questionNum <br />";
		$quizFileName = $_SESSION['quizFileName'];
		$rawQuestion = getLineFromFile($quizFileName, $questionNum);
		//echo var_dump($rawQuestion) . "<br/>";
		$rawQuestion = explode("#", $rawQuestion);
		$question = $rawQuestion[0];
		$possibleAnswers = explode(":",$rawQuestion[1]);
		$_SESSION['currentPossibleAnswers'] = $possibleAnswers;
		
		$numOfAnswers = count($possibleAnswers);
		// echo var_dump($possibleAnswers, $numOfAnswers) . "<br/>";
		$indexOfCorrectAnswer = (int) $rawQuestion[2];
		$_SESSION['currentCorrectAnswerIndex'] = $indexOfCorrectAnswer;
		$_SESSION['currentCorrectAnswer'] = $possibleAnswers[$indexOfCorrectAnswer];
		echo '<form action="/proj1/quiz/quiz.php" method="post">';
		echo "$question<br />";
		foreach($possibleAnswers as $key => $answer):
			if($key == 0):/* Check the first question. */
				echo "<input checked type='radio' name='answer' value='{$key}'> $answer <br />";
			else:
				echo "<input type='radio' name='answer' value='{$key}'> $answer <br />";
			endif;
		endforeach;
		echo '<input type="submit" value="Submit Answer" name="submitAnswer"> <br />';
		echo '</form>';		
	}
	
	function getQuizInfo($quizNum)
	{	
		$quizFile = "quizzes.txt";
		// echo var_dump($quizFile) . "<br/>";
		//echo getLineFromFile("quizzes.txt", $quizNum) . "<br/>";
		$line = getLineFromFile("quizzes.txt", $quizNum);
		$line = explode("#", $line);
		return $line;
	}
	
	function setSessionWithQuizInfo($quizInfo)
	{
		/* from quizzes.txt
		<QuizFileName>#<NumOfQuests>#<NumOfTakers>#<TotCorr>#<TotIncorr>
		pass exploded array
		*/
		$_SESSION['quizFileName'] = $quizInfo[0];
		$_SESSION['quizNumOfQuestions'] = (int)$quizInfo[1];
		$_SESSION['quizNumOfTakers'] = (int) $quizInfo[2];
		$_SESSION['quizTotalCorrect'] = (int) $quizInfo[3];
		$_SESSION['quizTotalIncorrect'] = (int) $quizInfo[4];
		$_SESSION['currentCorrectAnswerIndex'] = (int) -1;
	}
	
	function setSessionWithUserInfo()
	{
		$username = $_SESSION['username'];
		$_SESSION['userTakingQuiz'] = $username;
		$_SESSION['userCorrect'] = 0;
		$_SESSION['userIncorrect'] = 0;
		$_SESSION['usersCurrentQuestion'] = 1;
		
	}
	
	function rememberInCookieUserStartedTodaysQuiz()
	{
		$username = $_SESSION['username'];
		$timeOffset = 24*60*60*20;
		$todaysDate = (new DateTime())->format("m-d-Y");
		setcookie("$username" . "['lastQuiz']",$todaysDate, time() + $timeOffset, "/");
	}
	
	function getTodaysRandomQuizNumber()
	{
		/* We need to divide by a big number to not overflow the int space (32 bits) with the 192 bits of SHA-1 */
		$randint = (int) (hexdec( sha1((new DateTime)->format("m-d-Y")) ) / 10000000000000000000000000000000000000000000);
		$numOfQuizzes = getNumOfLinesFromFile("quizzes.txt");
		$todaysQuizNum = ($randint % $numOfQuizzes) + 1;
		return $todaysQuizNum;
	}
	
	function getNumOfLinesFromFile($filename)
	{
		$fp = fopen($filename, "r");
		if(flock($fp, LOCK_SH)):
			$numOfLines = 0;
			while($line = fgetss($fp, 512)):
				//echo $line . "<br/>";
				$numOfLines++;
			endwhile;
			flock($fp, LOCK_UN);
			fclose($fp);		
			return $numOfLines ;
		else: 
			echo "Trouble getting lock. Recursively calling getNumOfQuizzes() again.";
			sleep(1);
			getNumOfQuizzes();
		endif;
	}
	
	function getLineFromFile($filename, $lineNumber)
	{
		if($lineNumber < 1):
			echo "getLineFromFile() starts at line 1. Line $lineNumber was specified.<br />";
			return null;
		endif;
		// echo var_dump($filename) . "<br/>";
		$fp = fopen($filename, "r");
		if(flock($fp, LOCK_SH)):
			$currLineNumber = 1;
			while($line = fgetss($fp, 512)):
				if($currLineNumber == $lineNumber):
					return $line;
				else:
					$currLineNumber++;
				endif;
			endwhile;
			flock($fp, LOCK_UN);
			fclose($fp);		
			return null;
		else: 
			echo "Trouble getting lock. Recursively calling getLineFromFile() again.";
			sleep(1);
			getLineFromFile();
		endif;
	}
	
	function getAllLinesFromFile($filename)
	{
		$fp = fopen($filename, "r");
		if(flock($fp, LOCK_SH)):
			$allLines = array();
			$counter = 0;
			while($line = fgetss($fp, 512)):
				$allLines[$counter] = $line;
				$counter++;
			endwhile;
			flock($fp, LOCK_UN);
			fclose($fp);		
			return $allLines;
		else: 
			echo "Trouble getting lock. Recursively calling getLineFromFile() again.";
			sleep(1);
			getLineFromFile();
		endif;
	}

	
	
	
	

?>